<template>
  <van-picker
    title="性别"
    show-toolbar
    :columns="columns"
    :default-index="value"
    @change="onChange"
    @confirm="onConfirm"
    @cancel="$emit('close')"
  />
</template>

<script>
import { updateUserProfile } from "@/api/user.js";
export default {
  props: {
    value: {
      type: Number,
    },
  },
  data() {
    return {
      columns: ["男", "女"],
      gender: this.value,
    };
  },
  methods: {
    onChange(picker, value, index) {
      console.log(picker, value);
      // 得到所选性别的下标
      this.gender = index;
    },
    async onConfirm() {
      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
        duration: 0,
      });
      try {
        // 发起请求 改什么传什么参数
        await updateUserProfile({
          gender: this.gender,
        });
        // 传给父组件中的v-model
        this.$emit("input", this.gender);
        // 退出弹出层
        this.$emit("close");
        this.$toast.success("更新成功");
      } catch (err) {
        if (err.response && err.response.status === 401) {
          return this.$toast("用户未认证");
        }
        this.$toast("更新失败");
      }
    },
  },
};
</script>

<style>
</style>